import type {
  AddReq,
  DelReq,
  EditReq,
  InfoReq,
  UserPageRes,
} from '@fast-crud/fast-crud';

import type { AxiosRequestConfig } from '@vben/request';

import type { DefTenantModel } from './model/defTenantModel';

import type { PageParams, PageResult } from '#/api/types';

import { BaseEmployeeApi, listByBizId } from '#/api';
import { requestClient } from '#/api/request';
import { FileBizTypeEnum, ServicePrefixEnum } from '#/enums/commonEnum';
import { ContentTypeEnum } from '#/enums/httpEnum';
import { TenantStatusEnum } from '#/enums/system';

const MODULAR = 'defTenant';

export const DefTenantConfig = {
  Save: {
    url: `${ServicePrefixEnum.SYSTEM}/${MODULAR}`,
    method: 'POST',
  } as AxiosRequestConfig,
  Update: {
    url: `${ServicePrefixEnum.SYSTEM}/${MODULAR}`,
    method: 'PUT',
  } as AxiosRequestConfig,
};

export namespace DefTenantApi {
  /**
   * 分页查询
   */
  export async function page(
    params: PageParams<DefTenantModel.DefTenantPageQuery>,
  ) {
    return requestClient.post<PageResult<DefTenantModel.DefTenantResultVO>>(
      `${ServicePrefixEnum.SYSTEM}/${MODULAR}/page`,
      params,
    );
  }
  export async function get(id: string) {
    return requestClient.get<DefTenantModel.DefTenantResultVO>(
      `${ServicePrefixEnum.SYSTEM}/${MODULAR}/${id}`,
    );
  }
  export async function query(params?: DefTenantModel.DefTenantPageQuery) {
    return requestClient.post<DefTenantModel.DefTenantResultVO[]>(
      `${ServicePrefixEnum.SYSTEM}/${MODULAR}/query`,
      params,
    );
  }

  export async function updateStatus(
    params?: DefTenantModel.DefTenantPageQuery,
  ) {
    return requestClient.post<boolean>(
      `${ServicePrefixEnum.SYSTEM}/${MODULAR}/updateStatus`,
      params,
      { headers: { 'Content-Type': ContentTypeEnum.FORM_URLENCODED } },
    );
  }

  export async function initData(params?: DefTenantModel.DefTenantPageQuery) {
    return requestClient.post<boolean>(
      `${ServicePrefixEnum.SYSTEM}/${MODULAR}/initData`,
      params,
      { timeout: 2 * 60 * 1000 },
    );
  }

  export async function uploadFile(file: any) {
    return requestClient.post<boolean>(
      `${ServicePrefixEnum.SYSTEM}/${MODULAR}/upload`,
      file,
      { headers: { 'Content-Type': ContentTypeEnum.FORM_DATA } },
    );
  }
  export async function initDataSource(
    servicePrefix: string,
    tenantId: string,
  ) {
    return requestClient.get<boolean>(`${servicePrefix}/ds/initDataSource`, {
      params: { tenantId },
      timeout: 2 * 60 * 1000,
    });
  }

  export async function checkDs(servicePrefix: string, tenantId: string) {
    return requestClient.get<boolean>(`${servicePrefix}/ds/check`, {
      params: { tenantId },
      timeout: 2 * 60 * 1000,
    });
  }

  export async function save(params: DefTenantModel.DefTenantSaveVO) {
    return requestClient.post<DefTenantModel.DefTenantResultVO>(
      DefTenantConfig.Save.url as string,
      params,
    );
  }

  export async function update(params: DefTenantModel.DefTenantUpdateVO) {
    return requestClient.put<DefTenantModel.DefTenantResultVO>(
      DefTenantConfig.Update.url as string,
      params,
    );
  }
  export async function remove(data: string[]) {
    return requestClient.delete<boolean>(
      `${ServicePrefixEnum.SYSTEM}/${MODULAR}`,
      { data },
    );
  }

  export const pageRequest = async (
    pageQuery: PageParams<DefTenantModel.DefTenantPageQuery>,
  ): Promise<UserPageRes> => {
    return await page(pageQuery);
  };

  export const infoRequest = async (ctx: InfoReq): Promise<UserPageRes> => {
    const { row, mode } = ctx;

    if (mode === 'add') {
      return {};
    }
    const logos = await listByBizId({
      bizId: row.id,
      bizType: FileBizTypeEnum.DEF_TENANT_LOGO,
    });
    row.logo = logos[0]?.id;

    const area: string[] = [];
    if (row.provinceId) {
      area.push(row.provinceId);
    }
    if (row.cityId) {
      area.push(row.cityId);
    }
    if (row.districtId) {
      area.push(row.districtId);
    }
    row.area = area;

    return row;
  };

  export const addRequest = async (req: AddReq) => {
    const { form } = req;
    if (form.area) {
      form.provinceId = form.area?.[0];
      form.cityId = form.area?.[1];
      form.districtId = form.area?.[2];
    }
    return await save(form);
  };

  export const editRequest = async (ctx: EditReq) => {
    const { form } = ctx;
    if (form.area) {
      form.provinceId = form.area?.[0];
      form.cityId = form.area?.[1];
      form.districtId = form.area?.[2];
    }
    return await update(form);
  };

  export const updateStatusRequest = async (ctx: EditReq) => {
    const { form } = ctx;
    if (form.status === TenantStatusEnum.AGREED) {
      const param = {
        tenantId: form.id,
        reviewComments: form.reviewComments,
      };
      return await BaseEmployeeApi.toExamineTenantAndBindUser(param);
    }

    return await updateStatus(form);
  };
  export const initDataRequest = async (ctx: EditReq) => {
    const { form } = ctx;
    return await initData(form);
  };

  export const delRequest = async (ctx: DelReq) => {
    const { row } = ctx;
    return await remove([row.id]);
  };

  export const removeFn = async (ids: string[]) => {
    return await remove(ids);
  };
}
